from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class ProvinceView(View):
    def get(self, request):

        # 数据列表
        province_list = cache.get("province_list")

        if not province_list:
            province_list = []

            try:
                datas = Area.objects.filter(parent=None)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "数据库异常", "province_list": []})

            for d in datas:
                info = {}
                info["name"] = d.name
                info["id"] = d.id
                province_list.append(info)

            cache.set("province_list", province_list, 3600 * 12)
        return JsonResponse({"code": 0, "errmsg": "ok", "province_list": province_list})


class AreasCityView(View):
    def get(self, request, pid):

        ret_json = cache.get("%s_info" % pid)

        if not ret_json:
            ret_list = []
            ret_json = {"code": 0, "errmsg": "ok", "sub_data": {"subs": [], "p_id": pid, "pname": "xx"}}

            try:
                province = Area.objects.get(id=pid)

                ret_json["sub_data"]["pname"] = province.name

                infos = province.subs.filter()
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "数据库异常", "province_list": []})

            for info in infos:
                info_dict = {}
                info_dict["name"] = info.name
                info_dict["id"] = info.id
                ret_list.append(info_dict)

            ret_json["sub_data"]["subs"] = ret_list
            cache.set("%s_info" % pid, ret_json, 3600 * 12)
        return JsonResponse(ret_json)
